package com.fingerth.demo.net.retrofit

import android.util.Log
import com.fingerth.demo.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.lang.reflect.Type
import java.util.*
import java.util.concurrent.TimeUnit


object RetrofitUtils {
    private const val DEFAULT_TIMEOUT = 300L
    private const val TAG = "RetrofitUtils"

    private val builder: Retrofit.Builder
        get() = Retrofit.Builder().addConverterFactory(StringConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).client(okClient)

    private val okClient: OkHttpClient by lazy {
        val loggingInterceptor = if (BuildConfig.DEBUG) HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message -> Log.d(TAG, "OkHttp====Message: $message") }).apply { level = HttpLoggingInterceptor.Level.BODY } else null
        OkHttpClient.Builder() //设置超时
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).apply { loggingInterceptor?.let { addInterceptor(it) } }
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .build()
    }


    fun <T> retrofit(baseUrl: String, serviceClass: Class<T>): T = builder.baseUrl(baseUrl).build().create(serviceClass)

    private class StringConverter : Converter<ResponseBody, String> {
        @Throws(IOException::class)
        override fun convert(value: ResponseBody): String {
            return value.string()
        }

        companion object {
            val INSTANCE = StringConverter()
        }
    }

    private class StringConverterFactory : Converter.Factory() {
        // 我们只关实现从ResponseBody 到 String 的转换，所以其它方法可不覆盖
        override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? {
            return if (type === String::class.java) {
                StringConverter.INSTANCE
            } else null
            //其它类型我们不处理，返回null就行
        }

        companion object {
            private val INSTANCE = StringConverterFactory()
            fun create(): StringConverterFactory = INSTANCE
        }
    }
}